import type { Module } from 'vuex'
import { ILoginState } from './types'
import { IRootState } from '../types'
import { IAccount } from '@/service/login/types'
import { accountLoginRequest, requestUserInfoById, requestUserMenusByRoleId } from '@/service/login/login'
import localCache from '@/utils/cache'
import router from '@/router'
import { mapMenusToRoutes, mapMenuToPermission } from '@/utils/map-menus'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    saveToken(state, token: string) {
      state.token = token
    },
    saveUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    saveUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // 首页菜单的权限管理 根据菜单拿到映射的routes数据动态添加路由
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户操作权限
      const permissions = mapMenuToPermission(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    // 登录
    async accountLoginActions({ commit, dispatch }, payload: IAccount) {
      // 1. 登录并保存token
      const loginResult = await accountLoginRequest(payload)
      const { id, token } = loginResult.data
      commit('saveToken', token)
      localCache.setCache('token', token)

      // 拿到token后发送初始化请求(department/role等这些信息)
      dispatch('getInitialListData', null, { root: true })

      // 2. 请求用户信息并保存
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('saveUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)

      // 3. 请求用户菜单
      const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      const userMenus = userMenusResult.data
      commit('saveUserMenus', userMenus)
      localCache.setCache('userMenus', userMenus)

      // 4. 跳转到首页
      router.push('/main')
    },
    // 加载vuex数据
    loadStoreAction({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('saveToken', token)
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('saveUserInfo', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('saveUserMenus', userMenus)
      }

      // 拿到token后保存初始化请求的数据(department/role等这些信息)
      if (localCache.getCache('token')) {
        dispatch('getInitialListData', null, { root: true })
      }
    }
  }
}

export default loginModule
